package com.jh.user.service;

import cn.jh.common.exception.ServiceException;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.CommonsUtil;
import cn.jh.common.utils.DateUtil;
import cn.jh.common.utils.TokenUtil;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.jh.user.business.*;
import com.jh.user.pojo.*;
import com.jh.user.pojo.enums.UserGrade;
import com.jh.user.util.Util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

@Controller
@EnableAutoConfiguration
public class UserService {

	private static final Logger LOG = LoggerFactory.getLogger(UserService.class);

	@Autowired
	private UserBalanceBusiness userBalBusiness;

	@Autowired
	private BrandManageBusiness brandMangeBusiness;

	@Autowired
	private UserLoginRegisterBusiness  userLoginRegisterBusiness;

	@Autowired
	private BrandManageBusiness  brandManageBusiness;

	@Autowired
	private UserShopsBusiness userShopsBusiness;

	@Autowired
	private UserBankInfoBusiness userBankInfoBusiness;

	@Autowired
	private ThirdLeveDistributionBusiness  thirdLevelBusiness;

	@Autowired
	private UserRoleResourceBusiness userRoleResourceBusiness;

	@Autowired
	private ChannelRateBusiness channelRateBusiness;

	@Autowired
	Util util;
	@Autowired
	private UserBusiness userBusiness;


	@RequestMapping(method= POST,value="/v1.0/user/find/newuser/num")
	public @ResponseBody Object findUsergetnewnum(HttpServletRequest request,
												  @RequestParam(value = "brand_id" , defaultValue = "-1", required = false) long brandId,
												  //开始时间
												  @RequestParam(value = "start_time",  required = false) String  startTime,
												  //结束时间
												  @RequestParam(value = "end_time",  required = false) String endTime
	){
		Date StartTimeDate = null;
		if(startTime != null  && !startTime.equalsIgnoreCase("")){
			StartTimeDate = DateUtil.getDateFromStr(startTime);
		}
		Date endTimeDate = null;
		if(endTime != null  && !endTime.equalsIgnoreCase("")){
			endTimeDate = DateUtil.getDateFromStr(endTime);
		}
		return CommonsUtil.returnSuccess("查询成功",
				userLoginRegisterBusiness.queryUserNumByBidandtime(brandId, StartTimeDate, endTimeDate));
	}

	//获取shops表中随机的userid
	@ResponseBody
	@RequestMapping(method= POST,value="/v1.0/user/query/randomuserid")
	public Object queryRandomUserid(HttpServletRequest request) {
		Random rand = new Random();
		try {
			String[] userIds = userShopsBusiness.queryRandomUseridByAll();
			String userId = userIds[rand.nextInt(userIds.length-1)];
			return CommonsUtil.returnSuccess("获取成功", userId);
		} catch (Exception e) {
			LOG.error(e.getMessage());
			return CommonsUtil.returnError("数据为空");
		}
	}

	//获取shops表中随机的 shop id
	@ResponseBody
	@RequestMapping(method= POST,value="/v1.0/user/query/randomshopid")
	public Object queryRandomShopId(HttpServletRequest request) {
		Random rand = new Random();
		try {
			String[] shopIds = userShopsBusiness.queryRandomShopIdByAll();
			String shopId = shopIds[rand.nextInt(shopIds.length-1)];
			return CommonsUtil.returnSuccess("获取成功", shopId);
		} catch (Exception e) {
			LOG.error(e.getMessage());
			return CommonsUtil.returnError("数据为空");
		}
	}

	@RequestMapping(method= POST,value="/v1.0/user/query/by/phone/and/brandid")
	public @ResponseBody Object findUserByPhoneAndBrandId(HttpServletRequest request,
														  @RequestParam(value="phone")String phone,
														  @RequestParam(value="brandId")String brandId){
		try {
			User model = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, Long.valueOf(brandId));
			if (model == null) {
				return CommonsUtil.returnError("无该用户,请确认该用户已注册!");
			}
			return CommonsUtil.returnSuccess("查询成功", model);
		} catch (Exception e) {
			LOG.error("根据phone和brandId查询用户异常,参数为phone="+phone+",brandId="+brandId+";" + e);
			return CommonsUtil.returnError("查询用户失败,请检查输入的参数是否正确");
		}
	}

	// 用户注销接口
	@RequestMapping(method = POST, value = "/v1.0/user/delete/deleteUser")
	@ResponseBody
	public Object offUserActive(HttpServletRequest request,
								@RequestParam(value = "phone",defaultValue="", required=false) String phone,
								@RequestParam(value = "brandId",defaultValue="-1", required=false) long brandid,
								@RequestParam(value = "id",defaultValue="-1", required=false) long userid) {
		if (("".equals(phone) || phone == null) && brandid == -1 && userid == -1) {
			return CommonsUtil.returnError("必须输入至少一种查询条件");
		} else if (userid == -1) {
			List<User> user = userLoginRegisterBusiness.queryUsersByPhone(phone);
			if (user.size() == 0) {
				return CommonsUtil.returnError("该用户不存在");
			} else {
				userid = user.get(0).getId();
			}
		} else if ((phone == null || "".equals(phone)) && brandid == -1) {
			LOG.info("============我是输入的userid============"+userid);
		}

		List<User> userLower = userLoginRegisterBusiness.findAfterUsers(userid);

		Brand brand = brandMangeBusiness.findBrandByManageid(userid);

		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/queryorderfailed";
		String result = "";
		try {
			requestEntity.add("userid", userid + "");
			result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("RESULT================" + result);
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}
		JSONObject jsonObject = JSONObject.fromObject(result);
		JSONArray resultArr = jsonObject.getJSONArray("result");

		UserAccount userAccount = userBalBusiness.queryUserAccountByUserid(userid);
		double userBalance = 0.00;
		if (userAccount == null) {
			userBalance = 0.00;
		} else {
			userBalance = userAccount.getBalance().doubleValue();
			if (userBalance == 0.0) {
				userBalance = 0.00;
			} else {
				userBalance += 9;
			}
		}

		uri = util.getServiceUrl("paymentchannel", "error url request!");
		url = uri.toString() + "/v1.0/paymentchannel/automaticrepaymenttask/find";
		try {
			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("userId", userid + "");
			result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("RESULT================" + result);
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}
		jsonObject = JSONObject.fromObject(result);
		String resultTask = "";
		if (!jsonObject.containsKey("result")) {
			resultTask = null;
		}

		if (userLower.size() != 0) {
			return CommonsUtil.returnError("该用户存在下级会员");
		}
		if (brand != null) {
			return CommonsUtil.returnError("brand表中存在该用户");
		}
		if (resultArr.size() != 0) {
			return CommonsUtil.returnError("该用户有待完成或已成功订单");
		}
		if (userBalance != 0.00) {
			return CommonsUtil.returnError("该用户余额不为0");
		}
		if (resultTask != null) {
			return CommonsUtil.returnError("该用户有还款任务");
		}

		//if (userLower.size() == 0 && brand == null && resultArr.size() == 0 && userBalance == 0.00 && resultTask == null) {

		uri = util.getServiceUrl("paymentchannel", "error url request!");
		url = uri.toString() + "/v1.0/paymentchannel/realname/delrealname";
		try {
			requestEntity = new LinkedMultiValueMap<>();
			requestEntity.add("userId", userid + "");
			result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("RESULT================" + result);
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}
		try {
			userLoginRegisterBusiness.delUserByUserid(userid);
		} catch (Exception e) {
			LOG.info(e.getMessage());
			LOG.info("result========================还没有删除user表中记录");
		}
		userLoginRegisterBusiness.delUserByUserId(userid);
		return CommonsUtil.returnSuccess("注销成功");
	}

	//代理商授权功能接口
	@RequestMapping(method = POST, value = "/v1.0/user/auto/oriphone/{token}")
	@ResponseBody
	public Object userAuthManage(HttpServletRequest request,
								 @PathVariable("token") String token,
								 //被授权者手机号
								 @RequestParam(value = "phone") String oriphone,
								 //参数权限
								 @RequestParam(value = "roleId") long roleid,

								 @RequestParam(value = "lower_level", defaultValue = "0", required = false) int lowerLevel) {

		Map map = new HashMap();

		long userId;
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}

		User userOri = userLoginRegisterBusiness.queryUserByPhone(oriphone);
		long userOriId = userOri.getId();

		Long[] str2 = getUseridArray(userId,lowerLevel);

		if (userOri !=null && ArrayUtils.contains(str2, userOriId)) {
			UserRole userroleAuto = userRoleResourceBusiness.UserRolepageByRUid(userId);
			UserRole userroleOri = userRoleResourceBusiness.UserRolepageByRUid(userOriId);
			long roleIdAuto = userroleAuto.getRoleId();
			long roleIdOri = 0;
			if (userroleOri == null) {
				roleIdOri = -1;
			}else {
				roleIdOri = userroleOri.getRoleId();
			}

			long[] roleName = {5,4,3,2,1};
			int indexAuto = 0;
			int indexOri = 0;
			int indexRoleid = 0;
			for (int i = 0; i < roleName.length; i++) {
				if (roleIdAuto == roleName[i]) {
					indexAuto = i;
				}
				if (roleid == roleName[i]) {
					indexRoleid = i;
				}
				if (roleIdOri != -1 && roleIdOri == roleName[i]) {
					indexOri = i;
				}else if (roleIdOri == -1) {
					indexOri = -1;
				}
			}
			if (indexAuto <= indexOri) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "该用户权限大于等于您的权限");
				return map;
			}
			try {
				if (userroleOri != null && indexOri < indexAuto && indexRoleid < indexAuto) {
					userRoleResourceBusiness.upuserRole(userOriId, roleid);
				}else if(indexOri < indexAuto && indexRoleid < indexAuto) {
					UserRole role = new UserRole();
					role.setCreateTime(new Date());
					role.setRoleId(roleid);
					role.setUserId(userOriId);
					role.setStatus("0");
					userRoleResourceBusiness.adduserRole(role);
				}else {
					LOG.info("=============您设置的权限大于等于您的权限===========");
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE, "该用户不存在且您设置的权限大于等于您的权限");
					return map;
				}
			} catch (Exception e) {
				LOG.info(e.getMessage());
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "设置时权限出现异常");
				return map;
			}
		}else {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "该用户不是您的直推或间推");
			return map;
		}
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		return map;
	}

	// 代理商费率设置接口
	@RequestMapping(method = POST, value = "/v1.0/user/update/channelrate/{token}")
	@ResponseBody
	public Object userUpdateChannelRate(HttpServletRequest request,
										@PathVariable("token") String token,
										@RequestParam(value = "phone") String phone,
										@RequestParam(value = "rate") BigDecimal rate,
										@RequestParam(value = "channelId") long channelid,
										@RequestParam(value = "lower_level", defaultValue = "0", required = false) int lowerLevel) {
		Map map = new HashMap();

		long userid;
		long userAutoBrandid;
		try {
			userid = TokenUtil.getUserId(token);
			userAutoBrandid = TokenUtil.getBrandid(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}

		User userOri = userLoginRegisterBusiness.queryUserByPhone(phone);
		long userOriId = userOri.getId();

		Long[] str2 = getUseridArray(userid,lowerLevel);

		if (userOri !=null && ArrayUtils.contains(str2, userOriId)) {
			ChannelRate channelRateOri = channelRateBusiness.findChannelRateByUserid(userOriId, channelid);
			ChannelRate channelRateAuto = channelRateBusiness.findChannelRateByUserid(userid, channelid);
			double channelrateAuto = channelRateAuto.getRate().doubleValue();
			double channelrateOri = channelRateOri.getRate().doubleValue();
			try {
				if (channelrateAuto < channelrateOri) {
					channelRateBusiness.updChannelRateBybrandidAndChannelidanduserId(rate, userAutoBrandid, channelid, userOriId);
				} else {
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE, "该用户费率低于您的费率");
					return map;
				}
			} catch (Exception e) {
				LOG.info(e.getMessage());
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "用户通道费率查询返回为null");
				return map;
			}
		}else {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "该用户不是您的直推或间推");
			return map;
		}
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		return map;
	}

	private Long[] getUseridArray(long userId, int lowerLevel) {
		List<User> users = new ArrayList<User>();
		List<User> iusers = new ArrayList<User>();
		Long[] str2 = { userId };
		for (int i = 1; lowerLevel == 0 ? (i > 0) : (i <= lowerLevel); i++) {
			StringBuilder sbd = new StringBuilder();
			iusers = userLoginRegisterBusiness.findInfoUsers(str2);
			if (iusers.size() == 0) {
				int userlength = users.size();
				str2 = new Long[userlength];
				for (int j = 0; j < userlength; j++) {
					long userj = users.get(j).getId();
					str2[j] = userj;
				}
				break;
			}
			for (User iuser : iusers) {
				users.add(iuser);
				sbd.append(iuser.getId() + ",");
			}
			if (sbd.length() > 0) {
				String[] str1 = sbd.toString().split(",");
				str2 = new Long[str1.length];
				int str1length = str1.length;
				for (int j = 0; j < str1length; j++) {
					str2[j] = Long.valueOf(str1[j]);
				}
			}
		}
		return str2;
	}

	//查询当前权限下所有直推下级会员的信息
	@RequestMapping(method = POST, value = "/v1.0/user/userrole/querybyroleid/{token}")
	@ResponseBody
	public Object queryOriRoleidByRoleid(HttpServletRequest request,
										 @PathVariable("token") String token,
										 @RequestParam(value = "roleId") long roleid) {
		Map map = new HashMap();

		long userid;
		try {
			userid = TokenUtil.getUserId(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}

		List<User> users = userLoginRegisterBusiness.findAfterUsers(userid);

		if (users.size() == 0) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "您没有直推下级会员！");
			return map;
		}

		int usersSize = users.size();
		Long[] usersid = new Long[usersSize];
		for (int i = 0; i < usersSize; i++) {
			usersid[i] = users.get(i).getId();
		}

		List<UserRole> userrole = userRoleResourceBusiness.findUserRoleByRoleid(usersid, roleid);
		int userroleSize = userrole.size();

		if (userroleSize == 0) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "没有下级会员被授权此权限！");
			return map;
		}

		List<Map> userInfo = new ArrayList<Map>();
		for (int i = 0; i < userroleSize; i++) {
			Map map1 = new HashMap();
			UserRole userRole = userrole.get(i);
			long userId = userRole.getUserId();
			map1.put("phone", userLoginRegisterBusiness.queryUserById(userId).getPhone());
			map1.put("userid", userId);
			map1.put("roleid", userRole.getRoleId());
			map1.put("status", userRole.getStatus());
			map1.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(userRole.getCreateTime()));
			userInfo.add(map1);
		}

		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "查询成功");
		map.put(CommonConstants.RESULT, userInfo);
		return map;
	}

	/**
	 * 等级升级
	 */
	@RequestMapping(method = POST, value = "/v1.0/user/upgrade/{token}")
	public @ResponseBody Object upGrade(@PathVariable(value = "token") String token,
										@RequestParam(value = "grade") int grade){
		UserGrade userGrade = UserGrade.of(grade);
		if (userGrade == null) {
			return CommonsUtil.returnError("等级信息有误，请确认后再升级");
		}
		try {
			long userId = TokenUtil.getUserId(token);

			User user = userBusiness.upGrade(userId, userGrade);
			if (user == null) {
				return CommonsUtil.returnError("升级失败，请稍后再试！");
			}
			return CommonsUtil.returnSuccess("恭喜您，升级成功！");
		} catch (ServiceException ex) {
			return CommonsUtil.returnError(ex.getMessage());
		} catch (Exception e) {
			return CommonsUtil.returnError("token无效");
		}
	}




}

